package cn.edu.repository.impl;

import cn.edu.entity.JournalEntity;
import cn.edu.repository.JournalRepository;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sun.util.resources.cldr.ebu.CurrencyNames_ebu;

import javax.swing.text.html.parser.Entity;
import java.util.List;


@Repository
public class JournalRepositoryImpl implements JournalRepository {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession(){
        return this.sessionFactory.openSession();
    }

    public JournalEntity load(Long id) {
        return (JournalEntity) getCurrentSession().load(JournalEntity.class,id);
    }

    public JournalEntity get(Long id) {
        return (JournalEntity) getCurrentSession().get(JournalEntity.class,id);
    }

    public List<JournalEntity> findAll() {
        Criteria criteria = getCurrentSession().createCriteria(JournalEntity.class);
        List list = criteria.list();
        return list;
    }

    public void persist(JournalEntity entity) {
        getCurrentSession().persist(entity);
    }

    public Long save(JournalEntity entity) {
        return (Long)getCurrentSession().save(entity);
    }

    public void saveOrUpdate(JournalEntity entity) {
        Session hbSession = getCurrentSession();
        hbSession.saveOrUpdate(hbSession.merge(entity));
    }

    public void delete(Long id) {

        Session currentSession = getCurrentSession();
        Transaction transaction = currentSession.beginTransaction();

        JournalEntity entity = (JournalEntity) currentSession.get(JournalEntity.class,id);
        currentSession.delete(entity);
        transaction.commit();
    }

    public void flush() {
        getCurrentSession().flush();
    }
}
